package com.doubledr.light_lock.fragments;

import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.doubledr.light_lock.R;
import com.doubledr.light_lock.SettingPwdActivity;
import com.doubledr.light_lock.Task.DecryptTask;
import com.doubledr.light_lock.adapters.FileListAdapter;
import com.doubledr.light_lock.utils.FileManager;
import com.doubledr.light_lock.utils.OpenFileUtils;
import com.doubledr.light_lock.utils.PathManager;
import com.doubledr.light_lock.utils.ResManager;
import com.doubledr.light_lock.utils.ShareRefHelper;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link IndexFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FolderFragment extends android.support.v4.app.Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    BaseAdapter mAdapter = null;
    ListView myView = null;
    Context mContext = null;

    public FolderFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SettingsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static IndexFragment newInstance(String param1, String param2) {
        IndexFragment fragment = new IndexFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        String rootPath = PathManager.getFilePath(this.getContext(), "files_lock");
        ShowFileDir(rootPath);
        mContext = this.getContext();
    }

    private void ShowFileDir(String rootPath) {
        list.clear();
        File file = new File(rootPath);
        File[] files = file.listFiles();

        for (File f : files) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("name", f.getName());
            map.put("img", ResManager.getIcon(f, this.getContext()));
            String time = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss")
                    .format(new Date(f.lastModified()));
            map.put("time", time);
            map.put("file", f);
            map.put("datetime", new Date(f.lastModified()));
            list.add(map);
        }
        Collections.sort(list, new CompareValues());
        //如果不是根文件夹，那么添加一个返回的文件夹
        if (!PathManager.getRootDir(this.getContext()).equals(file.getPath())) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("name", "..");
            map.put("img", ResManager.getDrawableRes(this.getContext(), "folder"));
            String time = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss")
                    .format(new Date(file.lastModified()));
            map.put("time", time);
            map.put("file", file.getParentFile());
            map.put("datetime", new Date(file.lastModified()));
            list.add(map);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_folder, container, false);
        //必须在这个方法后，才能findViewById
        myView = view.findViewById(R.id.folderList);
        //设置自定义的adapter
        mAdapter = new FileListAdapter(this.getContext(), list);
        myView.setAdapter(mAdapter);
        myView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Map<String, Object> mapItem = list.get(position);
                if (mapItem != null) {
                    final  File f = (File) mapItem.get("file");
                    if (f.isDirectory()) {
                        if(f.getName().contentEquals(mContext.getString(R.string.de_folder))){
                            final String pwdFolder = ShareRefHelper.getValue(ShareRefHelper.getFolderID());
                            if(!pwdFolder.contentEquals("")){
                                //设置了文件夹密码
                                android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext);
                                builder.setTitle(R.string.input_pwd);
                                View alertView = getLayoutInflater().inflate(R.layout.alert_input_layout,null);
                                final TextView txtInput = alertView.findViewById(R.id.edtPwdRq);
                                builder.setView(alertView);
                                builder.setCancelable(false);
                                builder.setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        String newPwd = txtInput.getText().toString();
                                        if(newPwd.trim().contentEquals("")){
                                            Toast toast=Toast.makeText(mContext,R.string.pwd_cannot_null,Toast.LENGTH_SHORT    );
                                            toast.setGravity(Gravity.CENTER, 0, 0);
                                            toast.show();
                                            return;
                                        }
                                        int pwd = Integer.parseInt(newPwd);
                                        if(pwd!=Integer.parseInt(pwdFolder)){
                                            Toast toast=Toast.makeText(mContext, R.string.pwd_incorrect,Toast.LENGTH_SHORT    );
                                            toast.setGravity(Gravity.CENTER, 0, 0);
                                            toast.show();
                                            return;
                                        }
                                        ShowFileDir(f.getPath());
                                        mAdapter.notifyDataSetChanged();
                                    }
                                });
                                builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                });
                                builder.show();
                            }
                            else{
                                ShowFileDir(f.getPath());
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                        else{
                            ShowFileDir(f.getPath());
                            mAdapter.notifyDataSetChanged();
                        }
                    } else {

                        String ext = FileManager.getExtensionName(f.getPath());
                        if(!ext.equalsIgnoreCase("ept")){
                            OpenFileUtils.openAndroidFile(f.getPath(),mContext);
                        }
                    }
                }
            }
        });
        ItemOnLongClick1();
        return view;
    }

    private class CompareValues implements Comparator<Map<String, Object>> {
        @Override
        public int compare(Map<String, Object> o1, Map<String, Object> o2) {
            Date d1 = (Date) o1.get("datetime");
            Date d2 = (Date) o2.get("datetime");
            return d1.getTime() > d2.getTime() ? -1 : 2;
        }
    }

    private void ItemOnLongClick1() {
        myView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {

            public void onCreateContextMenu(ContextMenu menu, View v,
                                            ContextMenu.ContextMenuInfo menuInfo) {

                AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;

                Map<String,Object> itemMap =  list.get(info.position);
                if(itemMap!=null){
                    File f = (File) itemMap.get("file");
                    String ext = FileManager.getExtensionName(f.getPath());
                    if(ext.equalsIgnoreCase("ept")){
                        menu.add(0, 0, 0, R.string.decrpt);
                    }
                    if(!f.isDirectory()){
                        menu.add(0, 1, 0, R.string.sendtoother);
                        menu.add(0, 2, 0, R.string.delete);
                    }
                }

            }
        });
    }

    // 长按菜单响应函数
    public boolean onContextItemSelected(MenuItem item) {

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
                .getMenuInfo();
        switch (item.getItemId()) {
            case 0:
                //解密操作
                final int pos = info.position;
                final Map<String,Object> itemMap =  list.get(pos);
                android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this.getContext());
                builder.setTitle(R.string.input_pwd);
                View view = getLayoutInflater().inflate(R.layout.alert_input_layout,null);
                final TextView txtInput = view.findViewById(R.id.edtPwdRq);
                builder.setView(view);
                builder.setCancelable(false);
                builder.setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String newPwd = txtInput.getText().toString();
                        if(newPwd.trim().contentEquals("")){
                            Toast toast=Toast.makeText(mContext,R.string.pwd_cannot_null,Toast.LENGTH_SHORT    );
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                            return;
                        }
                        int pwd = Integer.parseInt(newPwd);
                        if(itemMap != null){
                            DecryptTask newTask = new DecryptTask(mContext,pwd);
                            String orgFilePath = ((File)itemMap.get("file")).getPath();
                            String targetFilePath = PathManager.getDecrytDir(mContext);
                            String[] strings = {orgFilePath,targetFilePath};
                            newTask.execute(strings);
                        }
                    }
                });
                builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.show();
                break;

            case 1:
                // 转发
                int pos2 = info.position;
                Map<String,Object> itemMap3 =  list.get(pos2);
                File f = (File) itemMap3.get("file");
                shareFile(mContext,f);
                break;

            case 2:
                // 删除
                 int pos1 = info.position;
                Map<String,Object> itemMap2 =  list.get(pos1);
                if(itemMap2!=null){
                    showConfirmDlg(itemMap2);
                }
                break;

            default:
                break;
        }

        return super.onContextItemSelected(item);

    }
    public  void shareFile(Context context, File file) {
        if (null != file && file.exists()) {
            Uri fileUri = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                fileUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
            }
            else{
                fileUri = Uri.fromFile(file);
            }
            Intent share = new Intent(Intent.ACTION_SEND);
            share.putExtra(Intent.EXTRA_STREAM,fileUri);
            //share.setType("*.*");//此处可发送多种文件
            share.setType(getMimeType(file.getAbsolutePath()));
            share.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.startActivity(Intent.createChooser(share, "分享文件"));
        } else {
            //ToastUtils.showToast("分享文件不存在");
        }
    }

    // 根据文件后缀名获得对应的MIME类型。
    private  String getMimeType(String filePath) {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        String mime = "*/*";
        if (filePath != null) {
            try {
                mmr.setDataSource(filePath);
                mime = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
            } catch (IllegalStateException e) {
                return mime;
            } catch (IllegalArgumentException e) {
                return mime;
            } catch (RuntimeException e) {
                return mime;
            }
        }
        return mime;
    }
    public void showConfirmDlg(final Map<String,Object> item){
        AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
        builder.setTitle(R.string.tip);
        builder.setMessage(R.string.sure_to_delete);
        builder.setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                try{
                    File f = (File) item.get("file");
                    f.delete();
                    list.remove(item);
                    mAdapter.notifyDataSetChanged();
                }
                catch (Exception ex){

                }
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
            }
        });
        builder.show();
    }
}
